using UnityEngine;
using System.Collections.Generic;
using System.Diagnostics;
using System;
using Debug = UnityEngine.Debug;
using Random = UnityEngine.Random;

public class ResultManager : MonoBehaviour
{
    [Header("系统引用")]
    [SerializeField] private GameManager gameManager;
    [SerializeField] private DataManager dataManager;
    //todo：构建完UIManager后引入此处进行使用
    //[SerializeField] private UIManager uiManager;

    [Header("结算配置")]
    public ResultConfig resultConfig;

    private BattleResult currentResult;


    // 事件定义
    public static event Action<BattleResult> OnShowBattleResult;
    public static event Action<List<string>> OnShowRelicSelection;
    public static event Action<List<Card>> OnShowCardReward;
    

    private void Awake()
    {
        // 自动查找依赖
        if (gameManager == null) gameManager = FindObjectOfType<GameManager>();
        if (dataManager == null) dataManager = FindObjectOfType<DataManager>();
        //if (uiManager == null) uiManager = FindObjectOfType<UIManager>();
    }

    /// <summary>
    /// 处理战斗结算
    /// </summary>
    public void ProcessBattleResult(BattleResult result)
    {
        currentResult = result;

        if (result.isVictory)
        {
            ProcessVictoryRewards(result);
        }
        else
        {
            ProcessDefeatPenalty(result);
        }

        // 更新游戏状态
        UpdateGameState(result);

        // 显示结算界面
        StartCoroutine(DelayedInvokeResult(result, 2.3f));
    }

    private System.Collections.IEnumerator DelayedInvokeResult(BattleResult result, float delay)
    {
        yield return new WaitForSeconds(delay);

        OnShowBattleResult?.Invoke(result);
        Debug.Log("已触发OnShowBattleResult事件");
    }

    /// <summary>
    /// 胜利奖励处理
    /// </summary>
    private void ProcessVictoryRewards(BattleResult result)
    {
        PlayerData player = FindObjectOfType<PlayerData>();
        /*
        // FindObjectOfType 可能会找到 DefaultPlayerData，这是不对的
        // 最好的方式是让 BattleManager 把当前的 player 传过来
        // 假设这里我们找到了场景里的 player：
        PlayerData scenePlayer = FindObjectsOfType<PlayerData>()
            .FirstOrDefault(p => p.gameObject.scene.name == "SampleScene"); // 简单粗暴的找法，或者用Tag区分

        if (scenePlayer != null)
        {
            // 将战斗后的状态（血量等）回写到 BattleLoader (真身)
            scenePlayer.DeepCopyTo(BattleLoader.playerData);
        }*/
        // 基础学力奖励
        int baseGold = CalculateBaseGoldReward(result);
        player.gold += baseGold;

        // 学分奖励（只有学习节点提供）
        if (result.nodeType == NodeType.Learning)
        {
            int creditReward = CalculateCreditReward(result);
            player.credit += creditReward;
        }

        // 遗物奖励（挑战老师节点提供）
        if (result.nodeType == NodeType.ChallengeTeacher && result.isBossBattle)
        {
            GrantRelicReward(result);
        }

        // 卡牌奖励
        if (ShouldGrantCardReward(result))
        {
            GrantCardReward(result);
        }

        player.DeepCopyTo(BattleLoader.playerData);
        Debug.Log($"战斗胜利奖励: 学力+{baseGold}, 节点类型: {result.nodeType}");
    }

    /// <summary>
    /// 失败惩罚处理
    /// </summary>
    private void ProcessDefeatPenalty(BattleResult result)
    {
        PlayerData player = FindObjectOfType<PlayerData>();

        // 扣除部分学力
        int goldLoss = Mathf.Min(player.gold / 4, 50); // 最多损失25%，不超过50
        player.gold -= goldLoss;

        // 重置玩家状态（保留遗物）
        player.ResetForCombat();

        player.DeepCopyTo(BattleLoader.playerData);
        Debug.Log($"战斗失败惩罚: 学力-{goldLoss}");
    }

    /// <summary>
    /// 计算基础学力奖励
    /// </summary>
    private int CalculateBaseGoldReward(BattleResult result)
    {
        int baseReward = resultConfig.baseGoldReward;

        // 难度修正
        if (result.isBossBattle) baseReward *= 3;
        else if (result.isEliteBattle) baseReward *= 2;

        // 表现修正（剩余血量、回合数等）
        float performanceBonus = CalculatePerformanceBonus(result);
        baseReward = Mathf.RoundToInt(baseReward * performanceBonus);

        return baseReward;
    }

    /// <summary>
    /// 计算学分奖励
    /// </summary>
    private int CalculateCreditReward(BattleResult result)
    {
        int baseCredit = resultConfig.baseCreditReward;

        // 难度修正
        if (result.isBossBattle) baseCredit *= 5;
        else if (result.isEliteBattle) baseCredit *= 2;

        return baseCredit;
    }

    /// <summary>
    /// 计算表现加成
    /// </summary>
    private float CalculatePerformanceBonus(BattleResult result)
    {
        float bonus = 1.0f;

        // 血量奖励
        float healthRatio = (float)result.playerFinalHP / result.playerMaxHP;
        if (healthRatio > 0.8f) bonus += 0.2f;
        else if (healthRatio > 0.5f) bonus += 0.1f;

        // 回合数奖励（快速结束战斗）
        if (result.turnsTaken <= 3) bonus += 0.15f;
        else if (result.turnsTaken <= 5) bonus += 0.1f;

        return bonus;
    }

    /// <summary>
    /// 发放遗物奖励
    /// </summary>
    private void GrantRelicReward(BattleResult result)
    {
        List<string> availableRelics = resultConfig.GetRandomRelicRewards(3);
        // 这里应该打开遗物选择界面，让玩家三选一
        OnShowRelicSelection?.Invoke(availableRelics);
    }

    /// <summary>
    /// 发放卡牌奖励
    /// </summary>
    private void GrantCardReward(BattleResult result)
    {
        CardFactory cardFactory = FindObjectOfType<CardFactory>();
        List<Card> rewardCards = cardFactory.GetRandomRewardCards(3, Rarity.Uncommon);
        StartCoroutine(DelayedInvokeReward(rewardCards, 2.5f));
    }

    private System.Collections.IEnumerator DelayedInvokeReward(List<Card> rewardCards, float delay)
    {
        yield return new WaitForSeconds(delay);

        OnShowCardReward?.Invoke(rewardCards);
        Debug.Log("已触发OnShowCardReward事件");
    }

    /// <summary>
    /// 判断是否发放卡牌奖励
    /// </summary>
    private bool ShouldGrantCardReward(BattleResult result)
    {
        // 普通战斗有50%概率获得卡牌奖励，精英和Boss必得
        if (result.isBossBattle || result.isEliteBattle) return true;
        return Random.Range(0f, 1f) <= 1f;
    }

    /// <summary>
    /// 更新游戏状态
    /// </summary>
    private void UpdateGameState(BattleResult result)
    {
        GameState gameState = FindObjectOfType<GameState>();
        PlayerData player = FindObjectOfType<PlayerData>();
        if (result.isVictory)
        {
            // 移动到下一个节点
            gameState.currentMapNode = result.nextNodeId;

            // 检查学分是否满足Boss战要求
            if (player.credit >= resultConfig.creditRequirementForBoss)
            {
                gameState.canChallengeBoss = true;
            }
        }
        else
        {
            // 游戏结束处理
            gameManager.HandleGameOver();
        }

        // 保存游戏进度
        gameManager.SaveGame();
    }

    /// <summary>
    /// 确认奖励选择（由UI调用）
    /// </summary>
    public void ConfirmRewardSelection(RewardSelection selection)
    {
        GameState gameState = FindObjectOfType<GameState>();
        PlayerData player = FindObjectOfType<PlayerData>();
        if (selection.selectedCard != null)
        {
            // 添加选择的卡牌到牌组
            gameState.masterDeck.Add(selection.selectedCard);
            gameState.currentDeck.Add(selection.selectedCard);
            Debug.Log("已添加卡牌到牌组");
        }

        if (!string.IsNullOrEmpty(selection.selectedRelicId))
        {
            // 添加选择的遗物
            player.relics.Add(selection.selectedRelicId);
        }

        // 继续游戏流程
        gameManager.ReturnToMap();
    }

    
}